<template>
  <div v-loading="loading" class="section-container flex-x gap-3" style="min-height: 70vh;">
    <el-card :style="{ width: fixedWidth ? '300px' : 'auto' }">
      <div slot="header">

        <div class="flex-x justify-between gap-2">
          <course-select v-model="query.courseId" width-fixed init-select-first
            @change="handleCourseChange"></course-select>
          <el-button type="primary" size="small" @click="handleAdd">添加章节</el-button>
        </div>
      </div>

      <div class="flex-y mx--2">
        <section-tree ref="sectionTree" :data-list="treeData" @select="handleSectionChange"
          @addContent="handleAddContent" @rename="handleRename" @delete="handleDelete" @sort="handleSort" />
      </div>
    </el-card>

    <!-- 右边章节预览 -->
    <div class="flex-1">
      <section-preview :section="currentSection" 
        @uploadFile="handleUploadFile" 
        @addMd="handleAddMd" 
        @edit="handleEdit" />
    </div>

    <!-- 章节编辑 -->
    <section-dialog ref="sectionDialog" @success="handleSaveSuccess" />

    <!-- 添加内容 -->
    <add-content-dialog ref="addContentDialog" />

    <!-- 上传文件 -->
    <file-section-dialog ref="fileSectionDialog" @success="handleSaveSuccess" />

    <!-- 添加md文档 -->
    <md-section-dialog ref="mdSectionDialog" @success="handleSaveSuccess" />
  </div>
</template>

<script>
import CourseSelect from '@/components/admin/CourseSelect'
import SectionTree from './components/SectionTree.vue'
import SectionDialog from './components/SectionDialog.vue'
import AddContentDialog from './components/AddContentDialog.vue'
import SectionPreview from './components/SectionPreview.vue'
import FileSectionDialog from './components/form/FileSectionDialog.vue'
import MdSectionDialog from './components/form/MdSectionDialog.vue'
import api from '@/common/api'
import utils from '@/common/utils'

export default {
  name: 'CourseSectionList',
  components: {
    CourseSelect,
    SectionTree,
    SectionDialog,
    AddContentDialog,
    SectionPreview,
    FileSectionDialog,
    MdSectionDialog
  },
  props: {
    fixedWidth: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      loading: false,
      query: {
        courseId: this.$route.query.courseId || null,
        keyword: null,
      },

      sectionList: [],
      currentSection: {}
    }
  },
  computed: {
    treeData() {
      return utils.buildTreeWithParentId(this.sectionList)
    }
  },
  mounted() {
    if (this.query.courseId) {
      this.loadSectionList()
    }
  },
  methods: {
    async loadSectionList() {
      try {
        this.loading = true
        const params = { courseId: this.query.courseId, limit: 1000 }
        if (!params.courseId) {
          this.sectionList = []
          return
        }
        const { data } = await api.admin_getCourseSectionList(params)
        this.sectionList = data.data.records
      } finally {
        this.loading = false
      }
    },
    handleCourseChange(courseId) {
      this.query.courseId = courseId
      this.currentSection = {}
      this.loadSectionList()
    },
    handleSectionChange(section) {
      this.currentSection = section
    },

    // 添加章节
    handleAdd() {
      if (!this.query.courseId) {
        this.$message.error('请先选择课程')
        return
      }
      let parentId = 0
      if (this.currentSection) {
        parentId = this.currentSection.fileUrl ? this.currentSection.parentId : this.currentSection.id
      }
      this.$refs.sectionDialog.open({
        courseId: this.query.courseId,
        parentId: parentId,
        sortOrder: 0
      })
    },
    handleRename(section) {
      this.$refs.sectionDialog.open(section)
    },
    handleDelete(section) {
      const { id } = section
      this.$confirm('确定要删除吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        this.loading = true
        await api.admin_deleteCourseSection(id)

        // 删除sectionList中的section
        const index = this.sectionList.findIndex(item => item.id === id)
        if (index !== -1) {
          this.sectionList.splice(index, 1)
        }
        if (this.currentSection.id === id) {
          this.currentSection = {}
        }
        this.$nextTick(() => {
          this.$refs.sectionTree.expandById(section.parentId)
        })
      }).finally(() => {
        this.loading = false
      })
    },
    async handleSort(sortData) {
      try {
        this.loading = true
        await api.admin_sortCourseSection(sortData)
        this.$message.success('操作成功')
      } finally {
        this.loading = false
      }
    },

    // 保存章节
    handleSaveSuccess(section) {
      // 将section添加到sectionList中，遍历sectionList，如果id相同，则替换
      const index = this.sectionList.findIndex(item => item.id === section.id)
      if (index !== -1) {
        this.$set(this.sectionList, index, section)
      } else {
        this.sectionList.push(section)
      }
      if (section.id === this.currentSection.id) {
        this.currentSection = section
      }

      this.$nextTick(() => {
        this.$refs.sectionTree.expandById(section.parentId)
      })      
    },
    handleAddContent(section) {
      this.$refs.addContentDialog.open(section)
    },
    reloadSectionTree() {
      this.loadSectionList()
    },
    handleUploadFile(section) {
      this.$refs.fileSectionDialog.open(section)
    },
    handleAddMd(section) {
      this.$refs.mdSectionDialog.open(section)
    },
    handleEdit(section) {
      if (section.fileUrl) {
        if (section.fileType === 'md') {  
          this.$refs.mdSectionDialog.open(section, 'edit')
        } else {
          this.$refs.fileSectionDialog.open(section, 'edit')
        }
      } else {
        this.$refs.sectionDialog.open(section)
      }
    }
  }
}
</script>

<style scoped>
.section-container {
  margin-bottom: 12px;
  :deep(.el-card__body, .el-card__header) {
    padding: 18px 12px;
  }

  :deep(.el-card__header) {
    height: 68px;
  }
}
</style>
